package com.wx.exam.controller;

/**
 * @Author ychiha
 * @Date 2021/11/25 19:58
 * @Version 1.0
 */

import org.springframework.web.bind.annotation.*;
import org.springframework.http.MediaType;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping(value = "/download")
public class DownLoadController {

    // Content-Type(mp4)  ===>   video/mpeg4

    private String basePath = "D:\\study\\大四上\\考试\\微信小程序资源";

    /**
     * 下载图片
     * produces ==设置Spring返回的数据类型==> jpeg文件
     * GetMapping =>用户访问value网址时触发方法
     * @param path 文件路径
     * @param type 类型
     * @return
     */
    @GetMapping(value = "/{type}/{path}", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] test(@PathVariable("path") String path,
                       @PathVariable("type") String type){
        String realPath = basePath+"\\"+type+"\\"+path;
        File file = new File(realPath);
        FileInputStream inputStream = null;
        byte[] bytes = null;
        try {
            inputStream = new FileInputStream(file);
            bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
        } catch (Exception e) {
            //出现异常
            byte[] fail = {-1};
            return fail;
        }finally {
            //关闭流  释放资源
            try {
                inputStream.close();
            } catch (Exception e) {
            }
        }
        return bytes;
    }

    /**
     * 下载视频
     * produces ==设置Spring返回的数据类型==> mp4文件
     * GetMapping =>用户访问value网址时触发方法
     * @param path 文件路径
     * @return
     */
    @GetMapping(value = "/mp4/{path}", produces = "video/mpeg4")
    @ResponseBody
    public byte[] test(@PathVariable("path") String path){
        String realPath = basePath+"\\"+"mp4"+"\\"+path;
        File file = new File(realPath);
        FileInputStream inputStream = null;
        byte[] bytes = null;
        try {
            inputStream = new FileInputStream(file);
            bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
        } catch (Exception e) {
            //出现异常
            byte[] fail = {-1};
            return fail;
        }finally {
            //关闭流  释放资源
            try {
                inputStream.close();
            } catch (Exception e) {
            }
        }
        return bytes;
    }




}

